package com.uzai.console.common.ip;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liuqi
 * @date 2022年11月25日 11:14
 */
public class IPUtil {
    public static void main(String[] args) throws IOException {
        System.out.println(IPUtil.getIP());
    }
    /**
     * @Param
     * @Description 获取IP
     * @Date: 2021/5/11
     **/
    public static String getIP() throws IOException {
        String ip = null;
        String chinaZ = "http://ip.chinaz.com";
        String response = sendGet(chinaZ);
        //过滤出响应中外网IP
        ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        if (ip == null) {
            String newUrl = match(response, "window.location.href=\"(http://ip.chinaz.com.+)\"");
            response = sendGet(newUrl);
            ip = match(response, "\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
        }
        return ip;
    }
    /**
     * @Param str
     * @Param regex
     * @Description 正则过滤
     * @Date: 2021/5/11
     **/
    public static String match(String str, String regex) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }
    /**
     * @Param url
     * @Description 发送get请求
     * @Date: 2021/5/11
     **/
    public static String sendGet(String url) throws IOException {
        URL urlObject = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
        connection.connect();
        try (InputStream inputStream = connection.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder response = new StringBuilder();
            String str;
            while ((str = reader.readLine()) != null) {
                response.append(str);
            }
            return response.toString();
        } catch (Exception ex) {
        }
        return null;
    }
}
